/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mytdev.util.properties.formatters.impl;

import com.mytdev.util.properties.formatters.AbstractFormatter;
import java.text.ParseException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Yann D'Isanto
 */
public class LocaleFormatter extends AbstractFormatter<Locale> {

    private static final Pattern LOCALE_PATTERN = Pattern.compile("([a-z]{2})(_([A-Z]{2})(_(.+))?)?");

    private static final Locale ROOT_LOCALE = new Locale("");

    /**
     * Parses an Locale from the specified string then returns it.
     *
     * @param string the string to parse.
     * @return the parsed Locale.
     * @throws ParseException if an error occurs.
     */
    public Locale parse(String string) throws ParseException {
        Locale locale = null;
        if (string.length() == 0) {
            locale = ROOT_LOCALE;
        }
        Matcher matcher = LOCALE_PATTERN.matcher(string);
        if (!matcher.matches()) {
            throw new ParseException("invalid locale: " + string, 0);
        }
        switch (matcher.groupCount()) {
            case 1:
                locale = new Locale(matcher.group(1));
                break;
            case 3:
                locale = new Locale(matcher.group(1), matcher.group(3));
                break;
            case 5:
                locale = new Locale(matcher.group(1), matcher.group(3), matcher.group(5));
                break;

        }
        return locale;
    }
}
